package com.winning.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Java8 内置的四大和兴函数式接口
 *
 * Comsumer<T> ：消费型接口
 *          void accept(T t);
 *
 * Supplier<T> ：供给型接口
 *          T get();
 *
 * Function<T, R> ：函数型接口
 *          R apply(T t);
 *
 * Predicate<T> ：断言型接口
 *          boolean test(T t);
 */
public class TestLambda3 {

    @Test
    public void test1(){
        happy(10000d, m -> System.out.println("1234566" + m));
    }

    public void happy(Double money, Consumer<Double> consumer){
        consumer.accept(money);
    }

    @Test
    public void test2(){
        List<Integer> list = getNumList(10,() -> {
            Random random = new Random();
            return random.nextInt(20);
        });

        list.forEach(System.out::println);
    }

    public List<Integer> getNumList(int num, Supplier<Integer> sup){
        List<Integer> list = new ArrayList<>();

        for (int i = 0; i < num; i++) {
            list.add(sup.get());
        }

        return list;
    }

    @Test
    public void test3(){
        System.out.println(strHandler("abcdefg", x -> x.toUpperCase()));
    }

    public String strHandler(String str, Function<String, String> fun){
        return fun.apply(str);
    }

    @Test
    public void test4(){
        List<String> list = Arrays.asList("Hello", "yanghao", "Lambda", "www", "ok");
        list = filterStr(list, x -> x.length()> 3);
        list.forEach(System.out::println);
    }

    public List<String> filterStr(List<String> list, Predicate<String> pre){
        List<String> result = new ArrayList<>();
        for(String str : list){
            if(pre.test(str)){
                result.add(str);
            }
        }

        return result;
    }



}
